package load_balance

import (
	"errors"
	"fmt"
	"math/rand"
	"strings"
)

type RandomBalance struct {
	curIndex      int             //当前索引index
	targetSvcList []string        //目标服务器数组
	lbConf        LoadBalanceConf //观察主体
}

func (r *RandomBalance) Add(params ...string) error {
	if len(params) == 0 {
		return errors.New("param len 1 at least")
	}
	addr := params[0]
	r.targetSvcList = append(r.targetSvcList, addr)
	return nil
}

func (r *RandomBalance) Next() string {
	if len(r.targetSvcList) == 0 {
		return ""
	}
	r.curIndex = rand.Intn(len(r.targetSvcList))
	return r.targetSvcList[r.curIndex]
}

func (r *RandomBalance) Get(key string) (string, error) {
	return r.Next(), nil
}

func (r *RandomBalance) SetConf(lbConf LoadBalanceConf) {
	r.lbConf = lbConf
}

func (r *RandomBalance) Update() {
	if lbConf, ok := r.lbConf.(*LoadBalanceZkConf); ok {
		fmt.Println("Update get lbConf:", lbConf.GetLoadBalanceIpConf())
		r.targetSvcList = []string{}
		for _, ip := range lbConf.GetLoadBalanceIpConf() {
			r.Add(strings.Split(ip, ",")...)
		}
	}
	if lbConf, ok := r.lbConf.(*LoadBalanceCheckConf); ok {
		fmt.Println("Update get lbConf:", lbConf.GetLoadBalanceIpConf())
		r.targetSvcList = nil
		for _, ip := range lbConf.GetLoadBalanceIpConf() {
			r.Add(strings.Split(ip, ",")...)
		}
	}
}
